package com.fengmi.filter;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengmi.exception.JWTParseException;
import com.fengmi.jwt.JwtUtils;
import com.fengmi.jwt.RsaUtils;
import com.fengmi.user.SysUser;
import com.fengmi.vo.ResultVO;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.security.PublicKey;
import java.util.regex.Pattern;

/**
 * 作者：铁蛋
 * 时间：2021/10/22 20:02
 * 描述：永无Bug
 */
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst("token");
        //定义一个白名单
        String[] whites={"/user/login","/index/(.*)","/search/goods","/user/verifyToken"};
        for (String white : whites) {
            if(Pattern.matches(white,request.getPath().toString())){
                //放行
             return  chain.filter(exchange);
            }
        }

        if (StringUtils.isEmpty(token)){
            return response(response,new ResultVO(false,"令牌不能为空"));
        }
        //校验令牌的合法性
        try {
            PublicKey publicKey = null;
            try {
                publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa_pub").getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            SysUser UserInfo = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
            //将用户信息放入请求头中
            ServerHttpRequest newRequest = request.mutate().header("userInfo", JSONUtil.toJsonStr(UserInfo)).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();



            //放行
            return  chain.filter(newExchange);
        } catch (JWTParseException e) {
            e.printStackTrace();
            return response(response,new ResultVO(false,"无效令牌"));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private Mono<Void> response(ServerHttpResponse response, ResultVO res){
        //不能放行，直接返回，返回json信息
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());

        return response.writeWith(Flux.just(dataBuffer));//响应json数据
    }
}





